package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.SuiBianJieUtil;
import com.block.datapush.service.apipush.utils.ZhengShengUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 正升信息
 */
@Service
public class ZhengShenXinXiApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();

        String timestamp = String.valueOf(System.currentTimeMillis());


        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("app_id", pushApiKeyParam.getApiCode());
        paramMap.put("timestamp", timestamp);
        paramMap.put("mobile", memberSourceInfo.getMobileMd5());

        String token = pushApiKeyParam.getApiSecret();
        String sign = makeSign(paramMap, token);

        paramMap.put("sign", sign);


        log.info("【正升信息】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【正升信息】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        log.info("撞库结果resultObject : {}",resultObject);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" );
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "20000")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        String timestamp = String.valueOf(System.currentTimeMillis());

        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("app_id", pushApiKeyParam.getApiCode());
        paramMap.put("timestamp", timestamp);
        paramMap.put("mobile", memberSourceInfo.getMobile());
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("city", city);
        paramMap.put("age", memberSourceInfo.getAge().toString());
        paramMap.put("amount", ZhengShengUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("sesame_score", BaseTypeInfoEnum.Zhima.getNameByValue(memberSourceInfo.getZhima()));
        paramMap.put("apply_time", memberSourceInfo.getCreateTime().toString());
        paramMap.put("house", ZhengShengUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("car", ZhengShengUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("policy", ZhengShengUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("sex", memberSourceInfo.getSex().toString());
        paramMap.put("careers", memberSourceInfo.getGongzuo()=="gz002"?"2":"1");
        paramMap.put("wage", memberSourceInfo.getGongzuo()=="gz002"?"1":"2");
        paramMap.put("funds", ZhengShengUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("insurance", ZhengShengUtil.getshebao(memberSourceInfo.getShebao()));
        paramMap.put("credit", ZhengShengUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("remark", "花呗额度:"+BaseTypeInfoEnum.Huabei.getNameByValue(memberSourceInfo.getHuabei())
                +"/白条额度："+BaseTypeInfoEnum.Baitiao.getNameByValue(memberSourceInfo.getBaitiao()));

        String token = pushApiKeyParam.getApiSecret();
        String sign = makeSign(paramMap, token);

        paramMap.put("sign", sign);


        log.info("【正升信息】导单开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【正升信息】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" );
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "20000")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }



    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String makeSign(Map<String, String> args, String token) {
        if (args == null || token == null) {
            return "";
        }

        Map<String, String> sortedArgs = new TreeMap<>(args);

        StringBuilder signStr = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedArgs.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (value != null && !value.isEmpty()) {
                signStr.append(key).append(value);
            }
        }

        System.out.println(signStr.toString());

        return md5(md5(signStr.toString()) + token).toUpperCase();
    }

    private static String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
}
